package com.ytc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 详细介绍类情况.
 *
 * @ClassName PayController
 * @Author zk
 * @Date 2023/1/14
 * @Version 1.0
 */
@Controller
public class PayController {
    //    @Autowired
//    private DonaItemService donaItemService;
//    @Autowired
//    private DonaService donaService;
    //appid
    private final String APP_ID = "2021000122608213";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCAp2tnXt+46fJO77sc2CnEq07OXXQneyG7zoioB7qXyvCp2rj6OSP+uK2YBOkDQES7Mikcu2Kmz8GhCBWh4uKJS2ZeSZlrcjQlEs6TEl1A6xNDQRkJ4zkpcWPSt2/AAHHcCfnK5AF1I9Sw3m0jrBXU4s4UOLXKSJIw8kkvuRUGdW+zRIfdAxLXk93EOpY3LRL9HJqToPoRkvvtyL979xjZ1rfzNkvHE3dVwq13nlupEgf+2ZQpz3d5a5JW/AFUKF6SFJZ4IDM4v+XsVgA5gSlQXYo9swLnsvJzBrZF8ErLqIlv0ok8iz7y9kgBKiXOM5aYeejfFlZa8dIGGt3TpLHhAgMBAAECggEAc4Pfb+VDw2hrZGzj+LYuaqPWEnzeukRYuaRsF1M5OunAxQHabPG5XBC97W0bOwwNqncTavTlUxnfpZL4uW5aMSQ+OhKjalIUd+U3Dd7DVHK9zPk6XiJjRM7G7oA+GotLsGJUotOua1tMsbJFFG6C+67ZklaJA6O9f61MAUmRk0XAqNGbFGbsYPAIHgU2lELtm/SqKHVjp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PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgKdrZ17fuOnyTu+7HNgpxKtOzl10J3shu86IqAe6l8rwqdq4+jkj/ritmATpA0BEuzIpHLtips/BoQgVoeLiiUtmXkmZa3I0JRLOkxJdQOsTQ0EZCeM5KXFj0rdvwABx3An5yuQBdSPUsN5tI6wV1OLOFDi1ykiSMPJJL7kVBnVvs0SH3QMS15PdxDqWNy0S/Ryak6D6EZL77ci/e/cY2da38zZLxxN3VcKtd55bqRIH/tmUKc93eWuSVvwBVChekhSWeCAzOL/l7FYAOYEpUF2KPbMC57Lycwa2RfBKy6iJb9KJPIs+8vZIASolzjOWmHno3xZWWvHSBhrd06Sx4QIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8082/user/returnUrl";

    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") float dona_money,
                         @RequestParam("dona_id") int dona_id) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",dona_id);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,"ghjk");
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

}
